package com.XZDP.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.XZDP.entity.ShopType;
import com.XZDP.mapper.ShopTypeMapper;
import com.XZDP.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.XZDP.utils.CacheUtils;
import com.XZDP.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MyUtils myUtils;
    @Autowired
    private CacheUtils cacheUtils;

    /**
     * redis缓存查询商铺类型  key->shop-type:*
     *
     * @return
     */
    @Override
    public List<ShopType> GetShopType() {
        //查询redis是否有数据
        Set<String> keys = redisTemplate.keys("shop-type:*");
        if (keys.isEmpty()) {
            //redis中没有数据,查询数据库
            List<ShopType> sort = query().orderByAsc("sort").list();
            //存入redis
            for (int i = 0; i < sort.size(); i++) {
                Map<String, Object> map = BeanUtil.beanToMap(sort.get(i));
                Map<String, String> StringMap = myUtils.ReturnStringMap(map);
                redisTemplate.opsForHash().putAll("shop-type:" + i, StringMap);
            }
            return sort;
        }
        //redis查询到数据
        List<ShopType> list = new ArrayList<>();
        System.out.println(keys);
        // 遍历每个键并获取对应的哈希值
        for (String key : keys) {
            Map<Object, Object> ShopvaluesMap = redisTemplate.opsForHash().entries(key);
            //将其转换回shop对象
            ShopType shopType = BeanUtil.fillBeanWithMap(ShopvaluesMap, new ShopType(), false);
            list.add(shopType);
        }
        //排序输出
        list.sort(Comparator.comparing(ShopType::getSort));
        return list;
    }
}
